package top.i51213.fastaction.action.share;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Parcelable;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class IntentChooser {
    public interface Filter{
        boolean shouldAdd(ResolveInfo info );
    }
    private final Context context;
    private final Intent sharingIntent;

    public IntentChooser(Context context, Intent sharingIntent) {
        this.context=context;
        sharingIntent=new Intent(sharingIntent);
        this.sharingIntent=sharingIntent;
    }

    public Intent get(String title, Filter filter){
        return get(title,filter,PackageManager.MATCH_DEFAULT_ONLY);
    }

    public Intent get(String title, Filter filter, int flags){
        PackageManager pm = context.getPackageManager();
        System.out.println(sharingIntent);
        @SuppressLint("QueryPermissionsNeeded")
        List<ResolveInfo> activityList = pm.queryIntentActivities(sharingIntent, flags);
        List<Intent> targetIntents = new ArrayList<>();
        for (ResolveInfo info : activityList) {
            System.out.println(info);
            if (filter.shouldAdd(info)) {
                Intent target = new Intent(sharingIntent);
                String packageName = info.activityInfo.packageName;
                String className = info.activityInfo.name;
                target.setComponent(new ComponentName(packageName, className));
                System.out.println("add");
                targetIntents.add(target);
            }
        }
        if(targetIntents.size()==0){
            return new Intent().setComponent(new ComponentName(context.getPackageName(),"BadClass"));
        }
        Intent chooserIntent = Intent.createChooser(targetIntents.remove(0), title);
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetIntents.toArray(new Parcelable[]{}));
        return chooserIntent;
    }
}
